import React, { useState, useEffect, useCallback } from 'react';
import {
    StyleSheet,
    View,
    Image,
    Text,
    TouchableOpacity,
    Button,
    Modal,
    FlatList,
    TextInput,
    Alert,
    ActivityIndicator,
    ImageBackground,
    ScrollView
} from 'react-native';
import * as rootNavigation from '@/utils/rootNavigation';

import { connect } from 'react-redux';
import layoutStyle from '@/assets/styles/layout';
import tobeDone from '@/assets/images/tobeDone.png';
import apply from '@/assets/images/apply.png';
import done from '@/assets/images/done.png';
import draft from '@/assets/images/draft.png';
import right_down from '@/assets/images/right-down.png';
import { getProcessData, addProcessTask, getProcessTotal } from '@/apis/api';
import {
    APP_CODE as appCode,
} from '../../../app.json';
import StorageUtils from '@/utils/storageUtils';
import { useFocusEffect } from '@react-navigation/native';

import { useTranslation } from 'react-i18next';
let SetProcess = ({ navigation }) => {
    const { t } = useTranslation();
    const [modalVisible, setModalVisible] = useState(false);
    const [selectedProcess, setSelectedProcess] = useState(null);
    const [processList, setProcessList] = useState([]);

    const [searchText, setSearchText] = useState('');
    // const [filteredData, setFilteredData] = useState(processList);

    const [total, setTotal] = useState(null);

    useFocusEffect(
        useCallback(() => {
            initDataTotal();

        }, []) // 空依赖表示只在焦点变化时执行
    );
    useEffect(() => {
        fetchData();
    }, [modalVisible]);

    const initDataTotal = async () => {
        const auth = await StorageUtils.getItem('auth');
        const localUserId = auth?.user_id || '';
        const res = await getProcessTotal({
            // namespace: appCode,
            userId: localUserId
        });
        setTotal(res?.data || null);
    }

    const [loading, setLoading] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [pagination, setPagination] = useState({
        pageNo: 1,
        pageSize: 10,
        total: 0,
        hasMore: true
    });
    // 获取数据
    const fetchData = async (isLoadMore = false) => {

        if ((!isLoadMore && loading) || (isLoadMore && !pagination.hasMore)) return;

        const currentPage = isLoadMore ? pagination.pageNo + 1 : 1;

        try {
            isLoadMore ? setLoadingMore(true) : setLoading(true);

            const params = {
                pageNo: currentPage,
                pageSize: pagination.pageSize,
                name: searchText,
                // namespace: appCode
            };

            const res = await getProcessData(params);

            setProcessList(prev =>
                isLoadMore ? [...prev, ...res.data.records] : res.data.records
            );

            setPagination({
                ...pagination,
                pageNo: currentPage,
                total: res.data.total,
                hasMore: res.data.records.length >= pagination.pageSize
            });
        } catch (error) {
            // Alert.alert(t('sys_error'), error.message);
        } finally {
            isLoadMore ? setLoadingMore(false) : setLoading(false);
        }
    };
    // 防抖搜索函数
    const debounce = (func, delay) => {
        let timer;
        return function (...args) {
            clearTimeout(timer);
            timer = setTimeout(() => func.apply(this, args), delay);
        };
    };

    // 搜索防抖处理
    useEffect(() => {
        const debouncedSearch = debounce(() => {
            setPagination(prev => ({ ...prev, pageNo: 1 }));
            fetchData();
        }, 500);

        debouncedSearch();
        return () => debouncedSearch.cancel?.();
    }, [searchText]);

    // 加载更多
    const handleLoadMore = () => {
        if (pagination.hasMore && !loadingMore) {
            fetchData(true);
        }
    };

    // 渲染底部加载指示器
    const renderFooter = () => {
        if (!loadingMore) return null;
        return (
            <View style={styles.footer}>
                <ActivityIndicator size="small" color="#2a50d7" />
                <Text style={styles.loadingText}>{t('sys_loading')}</Text>
            </View>
        );
    };


    const handleSelect = async (item) => {
        setSelectedProcess(item);

        setTimeout(() => {
            setModalVisible(false);
        }, 800)

        // 新增流程 逻辑 -- 跳转表单页 
        const res = await addProcessTask(item.code);
        const queryString = `?path=${res?.data?.formCode}&name=${res?.data?.name}&flowCode=${res?.data?.code}&type=form&actionType=ProessCenter`;
        rootNavigation.replace('ProessForm', {
            query: queryString,
            appCode: item?.namespaceCode
        });
    };



    const tabList = [{
        title: t('sys_myToDone'),
        icon: tobeDone,
        type: 'myToDone'
    }, {
        title: t('sys_myApply'),
        icon: apply,
        type: 'myApply'
    }, {
        title: t('sys_myDone'),
        icon: done,
        type: 'myDone'
    }, {
        title: t('sys_myDraft'),
        icon: draft,
        type: 'myDraf'
    }];

    const handleToDetail = (tab) => {
        rootNavigation.push(tab.type);
    };

    // 新增流程 打开弹框
    const handleToAdd = () => {
        setModalVisible(true);
        setSelectedProcess(null);
        setSearchText('');
    };
    useEffect(() => {
        navigation.setOptions({
            headerShown: true,
            headerBackVisible: true,
        });
    }, []);

    return (
        <View style={styles.container}>
            {/* <View>
                <Image style={styles.top} source={require('@/assets/images/process_top.png')} />
                <Text style={styles.top_title}>流程中心</Text>
            </View> */}
            <ScrollView>
                <ImageBackground
                    source={require('@/assets/images/process_top.png')}
                    style={styles.background}
                    resizeMode='cover'
                >
                    <Text style={styles.titleOnBackground}>{t('sys_processCenter')}</Text>
                </ImageBackground>
                <View style={styles.main}>
                    <Text style={styles.main_title}>{t('sys_processClass')}</Text>
                    <View>
                        {
                            tabList.length > 0 && tabList.map(tab => {
                                return (
                                    <TouchableOpacity
                                        key={tab.type}
                                        onPress={() => handleToDetail(tab)}
                                    >
                                        <View style={styles.card}>
                                            <View style={styles.card_main}>
                                                <Image source={tab.icon} />
                                                <Text>{tab.title}</Text>
                                            </View>
                                            {total && tab.type == 'myToDone' ? (<Text style={styles.totalBox}>{total}</Text>) : (<Image source={right_down} />)}

                                        </View>
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                </View>
            </ScrollView>
            
            <View style={styles.footer}>
                <TouchableOpacity
                    style={styles.customButton}
                    onPress={handleToAdd}
                >
                    <Text style={styles.buttonText}>{t('sys_addProcess')}</Text>
                </TouchableOpacity>
            </View>
            {/* 下拉弹窗 */}
            <Modal
                visible={modalVisible}
                transparent={true}
                animationType="fade"
                onRequestClose={() => setModalVisible(false)}
            >
                <TouchableOpacity
                    style={styles.modalOverlay}
                    activeOpacity={1}
                    onPress={() => setModalVisible(false)}
                >
                    <View style={styles.modalContent}>
                        <Text style={styles.modalTitle}>{t('sys_selectProcess')}</Text>
                        {/* 搜索框 */}
                        <TextInput
                            style={styles.searchInput}
                            // placeholder="搜索..."
                            placeholder={t('sys_select')}
                            value={searchText}
                            onChangeText={setSearchText}
                            autoFocus={true}
                        />

                        {/* 列表 */}
                        <View style={styles.listContainer}>
                            <FlatList
                                data={processList}
                                keyExtractor={(item) => item.id}
                                renderItem={({ item }) => (
                                    <TouchableOpacity
                                        style={[
                                            styles.processItem,
                                            selectedProcess?.id === item.id && styles.selectedItem,
                                        ]}
                                        onPress={() => handleSelect(item)}
                                    >
                                        <Text style={styles.processText}>{item.name}</Text>
                                        {selectedProcess?.id === item.id && (
                                            <Text style={styles.checkmark}>✓</Text>
                                        )}
                                    </TouchableOpacity>
                                )}
                                ItemSeparatorComponent={() => (
                                    <View style={styles.separator} />
                                )}
                                ListEmptyComponent={
                                    <Text style={styles.emptyText}>{t('sys_noMatchRes')}</Text>
                                }
                                ListFooterComponent={renderFooter}
                                onEndReached={handleLoadMore}
                                onEndReachedThreshold={0.2}
                                removeClippedSubviews={true}
                                initialNumToRender={5}
                                windowSize={10}
                            />
                        </View>
                    </View>
                </TouchableOpacity>
            </Modal>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F3F4F8',
        position: 'relative',
    },
    main: {
        paddingHorizontal: 10,
        marginBottom: 72
    },
    main_title: {
        color: '#000',
        paddingTop: 10,
    },
    background: {
        justifyContent: 'center',
        alignItems: 'flex-start',
        // flex: 1,
        height: 141,
    },
    titleOnBackground: {
        fontSize: 28,
        color: '#000',
        fontWeight: 700,
        marginLeft: 20
    },
    card: {
        backgroundColor: '#fff',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderRadius: 8,
        paddingVertical: 15,
        paddingHorizontal: 10,
        marginVertical: 6,
    },
    card_main: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        gap: 10,
    },
    footer: {
        position: 'absolute',
        bottom: 0,
        width: '100%',
        backgroundColor: '#fff',
        height: 72,
        paddingVertical: 15,
        paddingHorizontal: 10,
    },
    customButton: {
        height: 50,
        backgroundColor: '#2a50d7ff',
        // paddingVertical: 15, // 控制高度
        paddingHorizontal: 20,
        borderRadius: 5,
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttonText: {
        color: 'white',
        fontSize: 16,
        lineHeight: 50,
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: "rgba(0,0,0,0.5)",
        justifyContent: "center",
        alignItems: "center",
    },
    modalContent: {
        width: "80%",
        maxHeight: "60%",
        backgroundColor: "white",
        borderRadius: 8,
        overflow: "hidden",
    },
    listContainer: {
        maxHeight: 160,
    },
    modalTitle: {
        fontSize: 16,
        color: '#000',
        textAlign: 'center',
        lineHeight: 45,
    },
    processItem: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        padding: 15,
        backgroundColor: "#fff",
    },
    selectedItem: {
        backgroundColor: "#f0f7ff",
    },
    processText: {
        fontSize: 16,
    },
    checkmark: {
        color: "#2a50d7",
        fontWeight: "bold",
    },
    separator: {
        height: 1,
        backgroundColor: "#eee",
    },
    searchInput: {
        padding: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
        fontSize: 16,
    },
    emptyText: {
        padding: 12,
        textAlign: 'center',
        color: '#999',
    },
    totalBox: {
        width: 24,
        height: 24,
        backgroundColor: '#ca483eff',
        borderRadius: 5,
        color: '#fff',
        lineHeight: 24,
        textAlign: 'center',
    },
    loadingText: {
        marginTop: 5,
        color: '#666',
    },
});

export default connect()(SetProcess);
